trigger UpdateManagersEmail on Opportunity (before insert, before update) {
/*  Purpose: This workflow updates the User's Manager's email address from the User record 
             to the Opportunity in order to send notification emails to this person
    Created by: Sushmita Dey
*/
    // Initialize below variables in consideration of bulk triggering or mass records update
    set<Id> OpptyOwnersIds = new set<Id>();
    map<Id,Id> Owner2MgrMap = new map<Id,Id>();    
    map<Id,String> Mgr2EmailMap = new map<Id,String>();    
    Set<Id> AccounIds = new Set<Id>();
    RecordType rt = [Select Id, Name from RecordType where Name='ULA - Working Adults Layout'];
    // Get all Opportunties' owner Ids    
    for(Opportunity O: Trigger.New){
        OpptyOwnersIds.add(O.OwnerId);
        AccounIds.add(O.AccountId);
        System.debug('----------------111>>>>>> '+ o.RecordTypeId+ o.RecordType.Name);
    }
    Map<Id,Account> map_Account = new Map<Id,Account>([Select Id, Lead_Record_Type__c, RecordTypeId,RecordType.Name from Account where ID IN : AccounIds]); 
      for(Opportunity O: Trigger.New){
            if('ULA - Working Adults Prospective Student' == map_Account.get(O.AccountId).Lead_Record_Type__c)
            {
                O.RecordTypeId = rt.Id;
                
            }
      }      
  // Find their manager's Ids 
    for(User U: [Select id,ManagerId from User where Id In:OpptyOwnersIds]){
        If(U.ManagerId!=Null){
          Owner2MgrMap.put(U.Id, U.ManagerId);
        } 
    }  
    // Find manager's email address 
    If(!Owner2MgrMap.isEmpty()){ // Check's to see if manager's field on user record has been populated
        for(User M: [Select id,Email from User where Id In:Owner2MgrMap.values()]){
          Mgr2EmailMap.put(M.Id, M.Email);
        } 
    
        // Update Opportunties' with manager's email Ids using above maps
        for(Opportunity O: Trigger.New){
            if('ULA - Working Adults Prospective Student' == map_Account.get(O.AccountId).Lead_Record_Type__c)
            {
                O.RecordTypeId = rt.Id;
                
            }
        
            If(Owner2MgrMap.containsKey(O.OwnerId)){ // Checks to see if manager's field is populated
                O.Manager_s_Email_Address__c = Mgr2EmailMap.get(Owner2MgrMap.get(O.OwnerId));
            } else {
                O.Manager_s_Email_Address__c = ''; // Useful if manager's field is changed to null. Helps to keep records uptodate.
            }       
        }
    }
}